import 'package:safetymonitor/app/components/custom_tab_bar_widget.dart';
import 'package:safetymonitor/app/core/core.dart';
import 'package:safetymonitor/app/core/ext/widget_extension.dart';
import 'package:safetymonitor/app/core/utils/user_manager.dart';
import 'package:safetymonitor/generated/assets.dart';
import 'package:safetymonitor/modules/home/home_page/monitor/environmental_monitoring/view.dart';
import 'package:safetymonitor/modules/home/home_page/monitor/new_personnel_monitoring/view.dart';
import 'package:safetymonitor/modules/home/home_page/monitor/safe_production/view.dart';

import 'home_page_control.dart';

/// 首页
class HomePagePage extends StatefulWidget {
  const HomePagePage({super.key});

  @override
  State<HomePagePage> createState() => _HomePagePageState();
}

class _HomePagePageState extends State<HomePagePage>
    with SingleTickerProviderStateMixin {
  final control = Get.put(HomePageControl());

  ///五洲和总公司才有人员监测
  late final tabCtrl = TabController(
      length:
          control.userCompanyId == 100 || control.userCompanyId == 115 ? 2 : 1,
      vsync: this);

  @override
  void initState() {
    control.getAlarmCount();
    super.initState();
    tabCtrl.addListener(_handleTabSelection);
  }

  @override
  void dispose() {
    tabCtrl.removeListener(_handleTabSelection);
    tabCtrl.dispose();
    super.dispose();
  }

  void _handleTabSelection() {
    final int selectedIndex = tabCtrl.index;
    // 根据选中的索引执行相应操作
    print('Selected tab index: $selectedIndex');
    if (selectedIndex == 0) {
      control.getAlarmCount();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(AppDimens.sbh),
        child: Container(
          decoration: const BoxDecoration(
            gradient: LinearGradient(
              colors: [Color(0xff1F67E4), Color(0xff266CE5)], // 渐变颜色
              begin: Alignment.topCenter, // 渐变开始位置
              end: Alignment.bottomCenter, // 渐变结束位置
            ),
          ),
          // color:  const Color(0xff1F67E4), // 你可以自定义背景颜色
        ),
      ),
      body: NestedScrollView(
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return <Widget>[
            SliverToBoxAdapter(
                child: Container(
              color: AppColors.bg_color_grey,
              child: Column(
                children: [
                  Stack(
                    alignment: Alignment.topCenter,
                    children: [
                      Image.asset(
                        Assets.svgHomeBg,
                        width: AppDimens.sw,
                        height: 200.w,
                        fit: BoxFit.cover,
                      ),
                      Positioned(
                        top: 77.w,
                        child: Text(
                          '安全环保预警信息平台',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 26.sp,
                            fontWeight: FontWeight.w500,
                            shadows: const [
                              Shadow(
                                color: Colors.black54,
                                offset: Offset(0, 3),
                                blurRadius: 4,
                              ),
                            ],
                          ),
                        ),
                      ),
                      Positioned(
                        bottom: 0,
                        child: Stack(
                          alignment: Alignment.centerRight,
                          children: [
                            Image.asset(
                              Assets.imagesIconJinQing,
                              width: AppDimens.sw - 32.w,
                            ),
                            Positioned(
                              right: 20.w,
                              child: Container(
                                padding: EdgeInsets.symmetric(
                                    horizontal: 16.w, vertical: 5.w),
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(14),
                                ),
                                child: Row(
                                  children: [
                                    SvgPicture.asset(
                                      'assets/svg/day_jinqing_count_bg.svg',
                                      colorFilter: const ColorFilter.mode(
                                          Colors.red, BlendMode.srcIn),
                                      width: 20.w,
                                    ),
                                    AppGaps.hGap4,
                                    ValueListenableBuilder<int>(
                                      valueListenable: control.alarmCount,
                                      builder: (context, value, child) {
                                        return Text(
                                          '${control.alarmCount.value > 99 ? '99+' : control.alarmCount.value}',
                                          style: TextStyle(
                                              fontSize: 14.sp,
                                              color: Colors.red,
                                              fontWeight: FontWeight.w500),
                                        );
                                      },
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            Positioned(
                              bottom: 8.w,
                              left: 26.w,
                              child: ValueListenableBuilder<int>(
                                valueListenable: control.alarmCount,
                                builder: (context, value, child) {
                                  return Visibility(
                                    visible: control.alarmCount.value == 0,
                                    child: Text(
                                      '今天没有预警报警消息哦',
                                      style: TextStyle(
                                          fontSize: 13.sp,
                                          color: const Color(0xffB8948A)),
                                    ),
                                  );
                                },
                              ),
                            )
                          ],
                        ).clickOnce(control.goTodayPage),
                      ),
                    ],
                  ),
                  Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: AppDimens.dp9,
                    ),
                    child: GetBuilder(
                      init: control,
                      builder: (_) {
                        return Column(
                          children: [
                            _notice(),
                            AppGaps.vGap16,
                            _moduleBtn(),
                            // 中间的小模块(可配置)
                            _getApplicationModuleView(),
                            AppGaps.vGap16,
                          ],
                        );
                      },
                    ),
                  ),
                ],
              ),
            )),
            //吸收高度
            SliverOverlapAbsorber(
              handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
              sliver: SliverPersistentHeader(
                pinned: true,
                delegate: StickyHeader(
                  Container(
                    color: Colors.white,
                    child: CustomTabBarWidget(
                      ///五洲和总公司才有人员监测
                      padH: control.userCompanyId == 100 ||
                              control.userCompanyId == 115
                          ? null
                          : 160.w,
                      tabController: tabCtrl,
                      tabs: [
                        const Tab(text: '数据监测'),

                        ///五洲和总公司才有人员监测
                        if (control.userCompanyId == 100 ||
                            control.userCompanyId == 115)
                          const Tab(text: '人员监测'),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ];
        },
        body: _bottomModule(),
      ),
    );
  }

  // 公告
  Widget _notice() {
    return Column(
      children: [
        AppGaps.vGap16,
        Stack(
          children: [
            Container(
              height: AppDimens.dp40,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(4.r),
                  color: const Color(0x1aFF9C27)),
              child: Row(
                children: [
                  AppGaps.hGap12,
                  // SvgPicture.asset(Assets.svgHomeGoGao),
                  Text(
                    '公告',
                    style: TextStyle(
                      color: const Color(0xFFFF9C27),
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  AppGaps.hGap8,
                  Container(
                    width: 1.w,
                    height: 13.w,
                    color: const Color(0xFF3D4769),
                  ),
                  AppGaps.hGap8,
                  Expanded(
                    child: Text(
                      '${control.getNoticeBoardEntity.title}',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        color: const Color(0xFF3D4769),
                        fontSize: 14.sp,
                      ),
                    ),
                  ),
                  SvgPicture.asset('assets/svg/home_top_gg_right.svg'),
                  AppGaps.hGap12,
                ],
              ),
            ).click(control.goToNoticeBoard),
          ],
        ),
      ],
    );
  }

  // 模块按钮
  Widget _moduleBtn() {
    return SizedBox(
      // width: AppDimens.sw,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          SvgPicture.asset(
            'assets/svg/icon_home_top_left.svg',
            width: (AppDimens.sw - 20) / 3,
          ).clickOnce(control.goToNewAlarmWarningPage),
          SvgPicture.asset(
            'assets/svg/icon_home_top_center.svg',
            width: (AppDimens.sw - 20) / 3,
          ).clickOnce(control.goToDutyManagement),
          SvgPicture.asset(
            'assets/svg/icon_home_top_right.svg',
            width: (AppDimens.sw - 20) / 3,
          ).clickOnce(control.goToMaintenance),
        ],
      ),
    );
  }

  //系统类型标识，1-安全 2-环保 3-二者都有
  List<Widget> _showTabBottomView(int systemFlag) {
    switch (systemFlag) {
      case 1:
        return [
          AppGaps.vGap10,
          SafeProductionPage(),
          AppGaps.vGap100,
        ];
      case 2:
        return [
          AppGaps.vGap10,
          EnvironmentalMonitoringPage(),
          AppGaps.vGap100,
        ];
      case 3:
        return [
          AppGaps.vGap10,
          SafeProductionPage(),
          AppGaps.vGap20,
          EnvironmentalMonitoringPage(),
          AppGaps.vGap100,
        ];
      default:
        return [];
    }
  }

  /// 获取应用模块信息
  Widget _getApplicationModuleView() {
    return Wrap(
      spacing: 25.w, // 主轴(水平)方向间距
      runSpacing: 12.w, // 纵轴（垂直）方向间距
      // alignment: WrapAlignment.start, //沿主轴方向居中
      direction: Axis.horizontal,
      children: control.middleList.map<Widget>((item) {
        return SizedBox(
          width: 65.w,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              SvgPicture.asset(item.icon, height: 60.w, width: 60.w),
              Text(
                item.name,
                style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w500,
                  color: const Color(0xff3D4769),
                ),
              ),
            ],
          ),
        ).clickOnce(() {
          item.onTap();
        });
      }).toList(),
    );
  }

  /// 底部模块
  Widget _bottomModule() {
    return Container(
      padding: EdgeInsets.only(top: 45.w),
      child: TabBarView(
        controller: tabCtrl,
        children: [
          _getSafetyEnvironment(),

          ///五洲和总公司才有人员监测
          if (control.userCompanyId == 100 || control.userCompanyId == 115)
            _getPersonnelMonitoring(),
        ],
      ),
    );
  }

  // 数据监测
  Widget _getSafetyEnvironment() {
    return SingleChildScrollView(
      child: Column(
          children: _showTabBottomView(
              UserManager.rxUserEntity.value?.systemFlag ?? 0)
          // [
          //   AppGaps.vGap10,
          //   SafeProductionPage(),
          //   AppGaps.vGap20,
          //   EnvironmentalMonitoringPage(),
          //   AppGaps.vGap100,
          // ],
          ),
    );
  }

  // 人员检测
  Widget _getPersonnelMonitoring() {
    return Container(
      padding: EdgeInsets.only(top: 10.w),
      child: NewPersonnelMonitoringPage(),
    );
  }
}

///它允许你通过实现 SliverPersistentHeaderDelegate 来定义一个可以滚动的顶部区域，并且这个区域会在滚动过程中与页面其他部分有一定的交互
class StickyHeader extends SliverPersistentHeaderDelegate {
  StickyHeader(
    this.child,
  );

  final Widget child;

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return child;
  }

  @override
  double get maxExtent => 36.48;

  @override
  double get minExtent => 36.48;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return false;
  }
}
